package web

import (
	"net/http"
)

type BaseController struct {
	output Output
}

func (b *BaseController) Init(w http.ResponseWriter) {
	b.output = Output{ResponseWriter: w}
}

type Controller struct {
	BaseController
}

// Index 首页
func (c *Controller) Index(w http.ResponseWriter, r *http.Request) {
	c.Init(w)
	c.output.Success("welcome to xconsumer")
}

// GetTask 获取任务信息
func (c *Controller) GetTask(w http.ResponseWriter, r *http.Request) {
	c.Init(w)

	s := Server{}
	data, err := s.GetTask()
	if err != nil {
		c.output.Error(err.Error())
	}

	c.output.Success(data)
}

// UpdateTask 更新任务信息
// todo：需要优化为根据字段调整
func (c *Controller) UpdateTask(w http.ResponseWriter, r *http.Request) {
	c.Init(w)

	data := r.PostFormValue("data")
	s := Server{}
	err := s.UpdateTask(data)

	if err != nil {
		c.output.Error(err.Error())
	} else {
		c.output.Success("更新成功")
	}
}

// GetNodes 获取所有节点信息
func (c *Controller) GetNodes(w http.ResponseWriter, r *http.Request) {
	c.Init(w)

	s := Server{}
	children, err := s.GetNodes()
	if err != nil {
		c.output.Error(err.Error())
	}

	c.output.Success(children)
}

// GetNode 获取单个节点信息
func (c *Controller) GetNode(w http.ResponseWriter, r *http.Request) {
	c.Init(w)

	r.ParseMultipartForm(128)
	nodeName := r.PostForm.Get("node_name")

	s := Server{}
	data, err := s.GetNode(nodeName)
	if err != nil {
		c.output.Error(err.Error())
	}

	c.output.Success(data)
}

// GetNodeTask 获取节点任务信息
func (c *Controller) GetNodeTask(w http.ResponseWriter, r *http.Request) {
	c.Init(w)

	s := Server{}
	data, err := s.GetNodeTask()
	if err != nil {
		c.output.Error(err.Error())
	}

	c.output.Success(data)
}
